"""
产品相关序列化器
"""

from rest_framework import serializers
from pecco_site.models import (
    Product, ProductTranslation, ProductVariant,
    ProductOption, ProductOptionValue, Category
)


class ProductTranslationSerializer(serializers.ModelSerializer):
    """产品翻译序列化器"""
    class Meta:
        model = ProductTranslation
        fields = [
            'locale', 'name', 'short_desc', 'rich_desc',
            'default_product_details', 'general_specifications'
        ]


class CategorySimpleSerializer(serializers.ModelSerializer):
    """简化的分类序列化器，用于产品列表"""
    class Meta:
        model = Category
        fields = ['id', 'slug']


class ProductListSerializer(serializers.ModelSerializer):
    """产品列表序列化器"""
    categories = CategorySimpleSerializer(many=True, read_only=True)
    translations = ProductTranslationSerializer(many=True, read_only=True)
    cover_image_url = serializers.SerializerMethodField()
    hover_image_url = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = [
            'id', 'categories', 'cover_image_url', 'hover_image_url',
            'is_active', 'sort_order', 'usage', 'tag_new', 'tag_hot',
            'tag_featured', 'created_at', 'updated_at', 'translations'
        ]

    def get_cover_image_url(self, obj):
        if obj.cover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.cover_image.url)
            return obj.cover_image.url
        return None

    def get_hover_image_url(self, obj):
        if obj.hover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.hover_image.url)
            return obj.hover_image.url
        return None


class ProductDetailSerializer(serializers.ModelSerializer):
    """产品详情序列化器"""
    categories = CategorySimpleSerializer(many=True, read_only=True)
    category_ids = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Category.objects.all(),
        source='categories', write_only=True, required=False
    )
    translations = ProductTranslationSerializer(many=True, required=False)
    cover_image_url = serializers.SerializerMethodField()
    hover_image_url = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = [
            'id', 'categories', 'category_ids', 'cover_image', 'hover_image',
            'cover_image_url', 'hover_image_url', 'is_active', 'sort_order',
            'usage', 'tag_new', 'tag_hot', 'tag_featured', 'created_at',
            'updated_at', 'translations'
        ]

    def get_cover_image_url(self, obj):
        if obj.cover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.cover_image.url)
            return obj.cover_image.url
        return None

    def get_hover_image_url(self, obj):
        if obj.hover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.hover_image.url)
            return obj.hover_image.url
        return None

    def create(self, validated_data):
        translations_data = validated_data.pop('translations', [])
        categories = validated_data.pop('categories', [])

        product = Product.objects.create(**validated_data)
        product.categories.set(categories)

        for translation_data in translations_data:
            ProductTranslation.objects.create(product=product, **translation_data)

        return product

    def update(self, instance, validated_data):
        translations_data = validated_data.pop('translations', None)
        categories = validated_data.pop('categories', None)

        # 更新产品基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 更新分类
        if categories is not None:
            instance.categories.set(categories)

        # 更新翻译
        if translations_data is not None:
            # 删除现有翻译
            instance.translations.all().delete()
            # 创建新翻译
            for translation_data in translations_data:
                ProductTranslation.objects.create(product=instance, **translation_data)

        return instance


class ProductOptionValueSerializer(serializers.ModelSerializer):
    """产品选项值序列化器"""
    option_name = serializers.CharField(source='option.name', read_only=True)
    option_type = serializers.CharField(source='option.option_type', read_only=True)

    class Meta:
        model = ProductOptionValue
        fields = ['id', 'option', 'option_name', 'option_type', 'value', 'color_code']


class ProductVariantSerializer(serializers.ModelSerializer):
    """产品变体序列化器"""
    option_values = ProductOptionValueSerializer(many=True, read_only=True)
    image_url = serializers.SerializerMethodField()

    class Meta:
        model = ProductVariant
        fields = [
            'id', 'product', 'option_values', 'sku', 'image', 'image_url',
            'product_details', 'specifications', 'sort_order', 'is_active'
        ]

    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return None

